<template>
  <div class="hello">
    <button @click="send('1')">发消息</button>
    <div>{{returunData}}</div>
    <div>{{returunData.userName}}</div>
    <div>{{returunData.age}}</div>
    <h1>{{ msg }}</h1>
    <router-link to="testHtml" >跳转</router-link>
  </div>
</template>

<script>
import {connectWebsocket, closeWebsocket} from '../utils/websocket'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      returunData:[],
      socketone:'',
      num:''
    }
  },


  methods: {
    wsMessage(data) {
      console.log(data)
      // 这里写拿到数据后的业务代码
    },
    WsError(data) {
      console.log(data)
    },

    send(text){
      closeWebsocket()
      // 跟后端协商，需要什么参数数据给后台
      // const obj = {
      //   monitorUrl: 'xxxxxxxxxxxxx',
      //   userName: 'xxxxxxxxxx'
      // }
      // 发起ws请求
      // sendMessage('ws://localhost:8088/websocket/dhj', text, this.wsMessage, this.WsError)
      connectWebsocket(
        'ws://192.168.1.32:8088/websocket/dhj',
        text,
        this.wsMessage,
        this.WsError)
    },
    initWebSocket() {
      connectWebsocket(
        // 测试地址
        'ws://192.168.1.32:8088/websocket/dhj',
        // 传递给后台的数据
        {},
        // 成功拿到后台返回的数据的回调函数
        (data) => {
          this.returunData = JSON.parse(data)
          console.log(this.returunData.age)
          console.log('成功的回调函数, 接收到的data数据： ', data)
        },
        // websocket连接失败的回调函数
        () => {
          console.log('失败的回调函数')
        }
      );
    },

  },
  created() {
    this.initWebSocket()
  },
  destroyed() {
    closeWebsocket()
  },

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
